package cn.highedu.coolsharkhub.service.impl;

import cn.highedu.coolsharkhub.mapper.UserMapper;
import cn.highedu.coolsharkhub.pojo.entity.User;
import cn.highedu.coolsharkhub.pojo.vo.UserVO;
import cn.highedu.coolsharkhub.service.UserService;
import cn.highedu.coolsharkhub.service.exception.BlankParameterException;
import cn.highedu.coolsharkhub.service.exception.UserNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用户业务实现类
 * @author HighEDU
 */
@Service
public class UserServiceImpl implements UserService {
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserMapper userMapper;
    /**
     * 用户登录：如果登录成功，返回用户信息视图对象；如果登录失败，抛出异常
     * @param username 用户名
     * @param password 密码
     * @return 用户信息视图对象
     * @throws UserNotFoundException 用户不存在、密码错误
     * @throws BlankParameterException 参数为空
     */
    @Override
    public UserVO login(String username, String password) {
        if (username == null || username.trim().isEmpty()) {
            logger.warn("用户名不能为空");
            throw new BlankParameterException("用户名不能为空");
        }
        if (password == null || password.trim().isEmpty()) {
            logger.warn("密码不能为空");
            throw new BlankParameterException("密码不能为空");
        }
        User user = userMapper.selectUserByUsername(username);
        if (user== null) {
            logger.warn("用户不存在");
            throw new UserNotFoundException("用户不存在");
        }
        if (!user.password().equals(password)) {
            logger.warn("密码错误");
            throw new UserNotFoundException("密码错误");
        }
        return new UserVO(user.id(), user.username(), user.password(), user.role());
    }
}
